
package qualomelhor.server;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.UUID;
import javax.servlet.http.*; 

import qualomelhor.database.Usuario;
import qualomelhor.database.ParametrosSistema.OrigemLogin;
import qualomelhor.util.Util;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.User;

public class LoginFBServlet extends HttpServlet { 

	private static final long serialVersionUID = 0;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doPost(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { 

		resp.setContentType("Text/Plain");

		System.out.println("accessToken = " + req.getParameter("access_token"));
		String accessT = req.getParameter("accessToken");
		if (accessT == null) {
			accessT = (String)req.getAttribute("accessToken");
			if (accessT != null && accessT.length() <= 5) {
				accessT = null;
			}
		}

		if (req.getParameter("accessToken") != null) {
			User user = getUserInfo(req.getParameter("access_token"));
			resp.sendRedirect("/logado.jsp?nome=" + user.getName() + "&id=" + user.getId() + "&facebook=true");
			//imprimeUserInfo(resp, user);
		} else {

			String app_id = "";
			String app_secret = "";
			if (req.getServerName().equals("www.qual-o-melhor.com")) {
				app_id = "343538035658997";
				app_secret = "8023bbeef61df4d7d0d059c4e9440427";	
			} else if (req.getServerName().equals("www.which-is-better.net")) {
				app_id = "251470321613608"; 
				app_secret = "602baa2419a4306a1ab3d824201f9d82";
			} else if (req.getServerName().equals("www.witch-is-better.com")) {
				app_id = "251471681589048";
				app_secret = "4367064af22143b7a397751083c7edaf";
			} else if (req.getServerName().equals("localhost")) {
				app_id = "251470321613608"; 
				app_secret = "602baa2419a4306a1ab3d824201f9d82";			
			}

			String my_url = "http://" + req.getServerName() + "/loginFB";
			if (req.getServerName().equals("localhost")) {
				my_url = "http://" + req.getServerName() + ":8888/loginFB";
			}
			System.out.println("my_url = " + my_url);

			HttpSession session = req.getSession(true);

			String code = req.getParameter("code");

			System.out.println("code = " + code);

			if(code == null || code.equals("")) {
			     session.setAttribute("state", UUID.randomUUID().toString()); //CSRF protection
			     String dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
			       + app_id + "&redirect_uri=" + URLEncoder.encode(my_url, "UTF-8") + "&state="
			       + session.getAttribute("state");

			     //resp.getWriter().write("<script> top.location.href='" + dialog_url + "'</script>");
			     resp.sendRedirect(dialog_url);
			     System.out.println("Enviou a primeira solicitacao para autorizar e conectar...");
			} else {

				String reqState = req.getParameter("state");
				System.out.println("reqState_Request = " + reqState);

				String sessionState = (String)session.getAttribute("state");
				System.out.println("reqState_Session = " + sessionState);

				if (reqState != null && sessionState != null && reqState.equals(sessionState)) {
					String token_url = "https://graph.facebook.com/oauth/access_token?"
						+ "client_id=" + app_id + "&redirect_uri=" + URLEncoder.encode(my_url, "UTF-8")
						+ "&client_secret=" + app_secret + "&code=" + code;

					//$response = @file_get_contents($token_url);
					String response = Util.sendGETUrl2(token_url, "GET", "text/plain");

					System.out.println("response = " + response);

					if (!response.equals("")) {
						//parse_str($response, $params);
						HashMap<String, String> params = Util.parseMap(response);
						Iterator<Entry<String, String>> entry = params.entrySet().iterator();
						while (entry.hasNext()) {
							Entry<String, String> ent = entry.next();
							System.out.println("response.key = [" + ent.getKey() + "]");
							System.out.println("response.value = [" + ent.getValue() + "]");
						}

						User user = getUserInfo(params.get("access_token"));
						
						//Verificar se o usuario existe na base e adicionar caso nao exista
						DAO d = new DAO();
						Usuario u = d.getUsuarioFB(user.getId());
						if (u == null) {
							System.out.println("novo usuario do facebook sendo criado..");
							u = new Usuario(user.getEmail(), user.getId(), OrigemLogin.FACEBOOK.getSiteOrigem(), params.get("access_token"), "", user.getName(), user.getHometownName(), "", user.getLocale(), "", true, "", new Date());
						} else {
							System.out.println("atualizando usuario do facebook..");
							u.setNomeUsuario(user.getName());
							u.setEmail(user.getEmail());
							u.setCidade(user.getHometownName());
							u.setPais(user.getLocale());
							u.setAccessToken(params.get("access_token"));
						}
						d.gravaNovoUsuario(u);
						
						@SuppressWarnings("unchecked")
						HashMap<String, Object> mapSession = (HashMap<String, Object>)session.getAttribute("SESSIONVAR"); 

						if (mapSession == null) {
							mapSession = new HashMap<String, Object>(0);
						}

						mapSession.put("USUARIOATUAL", u);
						session.setAttribute("SESSIONVAR", mapSession);
						session.setAttribute("USUARIOATUAL", u);
						System.out.println("SETOU O USUARIO ATUAL: " + u.getNomeUsuario() + ", Admin:" + u.getAdmin());

						resp.sendRedirect("/logado.jsp?nome=" + u.getNomeUsuario() + "&id=" + user.getId() + "&facebook=true");
						//resp.sendRedirect("/testelogin");
						//imprimeUserInfo(resp, user);

						//String graph_url = "https://graph.facebook.com/me?access_token=" + params.get("access_token") + "&format=json";
						//System.out.println("graph_url = " + graph_url);

						//$user = json_decode(file_get_contents($graph_url));
						//String graphResult = Util.sendGETUrl2(graph_url, "GET", "application/json");
						//System.out.println("graphResult = " + graphResult);

						/*
						JSONValue js = JSONParser.parseStrict(graphResult);
						JSONObject user = js.isObject();

						resp.getWriter().println("Hello " + user.get("name"));
						*/
						//resp.getWriter().println("graphResult = " + graphResult);
					} else {
						resp.getWriter().println("response em branco em relacao a chamada:<BR><BR>" + token_url);
					}
				} else {
					System.out.println("The state does not match. You may be a victim of CSRF.");
					//resp.getWriter().println("The state does not match. You may be a victim of CSRF.");
				}
			}
		}
	}

	private User getUserInfo(String accessToken) {
		FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
		User user = facebookClient.fetchObject("me", User.class);
		System.out.println("user name = " + user.getName());
		System.out.println("email = " + user.getEmail());
		System.out.println("locale = " + user.getLocale());
		System.out.println("user id = " + user.getId());
		return user;
	}
	
	private void imprimeUserInfo(HttpServletResponse resp, User u) {
		try {
			resp.getWriter().println(u.getName());
			resp.getWriter().println("id = " + u.getId());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}